package com.demoworld;

import org.junit.Test;

/**
 * Created by francis on 2017/7/5.
 * 队列的顺序存储实现
 */
public class JArrayQueue implements IQueue {
    public JArrayQueue(int maxLength) {
        this.maxLength = maxLength;
        arr = new int[this.maxLength];
        tailIndex = -1;
    }

    private int[] arr;
    private int tailIndex;//当前队列的尾巴索引， 这个位置是最后一个数据
    private int maxLength;

    @Override
    public void push(int n) {
        if (tailIndex + 1 >= arr.length) {
            System.out.println("warn: stack is full");
            return;
        }
        tailIndex++;
        arr[tailIndex] = n;
    }

    @Override
    public int pop() {
        int result = arr[0];

        int[] tmp = arr;
        arr = new int[tmp.length - 1];
        copyArryTo(tmp, 1, arr);
        tailIndex--;

        return result;
    }

    @Override
    public boolean isEmpty() {
        return tailIndex == -1;
    }

    //从from 数组中 fromIndex这个下标开始拷贝数据到to数组
    private void copyArryTo(int[] from, int fromIndex, int[] to) {
        if (from == null || to == null || from.length == 0 || to.length == 0) {
            return;
        }
        int maxIndex = from.length - 1;
        if (from.length > to.length) {
            maxIndex = to.length - 1;
        }
        for (int i = 0; i <= maxIndex; i++) {
            to[i] = from[i + fromIndex];
        }
    }

    private void copyArryTo(int[] from, int[] to) {
        if (from == null || to == null || from.length == 0 || to.length == 0) {
            return;
        }
        int maxIndex = from.length - 1;
        if (from.length > to.length) {
            maxIndex = to.length - 1;
        }
        for (int i = 0; i <= maxIndex; i++) {
            to[i] = from[i];
        }
    }
}
